Writing Classes in PHP
<?php
class connect{
private $server = "localhost:3308";
private $user = "root";
private $pwd = "";
private $db = "test";
private $conn = null;
public function __construct(){
try{
$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db",$this->user,$this->pwd);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $sql."<br>".$e->getMessage();
}
}
public function getConnection(){
return $this->conn;
}
public function closeConnection(){
$conn = null;
}
}
<?php
require_once("connect.php");
class Fee{
private $total_amount;
private $program;
private $year;
private $con;
private $c;
public function __construct($tfee,$prog,$year){
$this->total_amount = $tfee;
$this->program = $prog;
$this->year = $year;
$this->con = new connect();
$this->c = $this->con->getConnection();
}
public function store(){
$stmt = $this->c->prepare("insert into fee(amt,prog,year) values(?,?,?)");
$stmt->execute([$this->total_amount,$this->program,$this->year]);
}
public function getFee($year,$prog){
$rql = "select amt,prog,year from fee where year =? and prog=?";
$stmt = $this->c->prepare($rql);
$stmt->execute([$year,$prog]);
$result = $stmt->fetchAll();
return $result;
}
}
<?php
require_once("connect.php");
require_once("fee.php");
if(isset($_POST["submit"])){
$amt = htmlspecialchars($_POST["amt"]);
$prog = htmlspecialchars($_POST["prog"]);
$year = htmlspecialchars($_POST["year"]);
echo "<p>Amount: ".$amt."</p>";
$f = new fee($amt,$prog,$year);
$f->store();
$res = $f->getFee(2024,"BIM");
foreach($res as $key=>$value){
echo "<p>".$key. " ".$value[0]." ".$value[1]."</p>";
}
}else{
echo "error";
}